package com.cvpoc.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrDocumentList;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.DispatchActionSupport;

import com.cvpoc.exception.BusinessException;
import com.cvpoc.service.SolrService;
import com.cvpoc.struts.form.SolrSearchForm;

public class SolrSearchAction extends DispatchActionSupport {
	
	public ActionForward rechercherCollaborateur(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		return mapping.findForward("successAfficherRechercheCollaborateur");
	}
	
	public ActionForward afficherCollaborateur(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		try {
			SolrSearchForm solarSearchForm = (SolrSearchForm) form;
			
			SolrService solrService = (SolrService) getWebApplicationContext().getBean("solrService");
			SolrServer solrServer	= solrService.solrServer();
			
			SolrQuery solrQuery		= new SolrQuery().
					setQuery(solarSearchForm.getSearchInput()).
					addSortField( "nom", SolrQuery.ORDER.asc ); 
	        
	        SolrDocumentList documents 	= solrService.SolrServerDocuments(solrServer, solrQuery);
			
	        if(documents.getNumFound() > 0) {
	        	request.setAttribute("collaborateurs", documents);
	        } else {
	        	return mapping.findForward("failureAfficherListeCollaborateur");
	        }
	        
	        return mapping.findForward("successAfficherListeCollaborateur");
		}catch (BusinessException e) {
			return mapping.findForward("failureAfficherListeCollaborateur");
		}
	}

}
